layui.use(['layer', 'form','table','configs','iconPicker'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        iconPicker = layui.iconPicker,
        config = layui.configs;

    //全局变量：表格列
    var cols = [
        {field: 'menuSort', title: '菜单排序', width: 100}
        , {field: 'menuId', title: '菜单ID', width: 100}
        , {field: 'menuName', title: '菜单名'}
        , {field: 'menuCode', title: '菜单代号'}
        , {field: 'menuTitle', title: '菜单显示名称'}
        , {field: 'menuUrl', title: '菜单url'}
        , {field: 'pMenuId', title: '上级菜单ID'}
        , {field: 'ioce', title: '菜单icon', width: 100, templet: function(d){
                return `<i class="iconfont layui-icon ${d.ioce}"></i>`
            }}
        , {fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#rowOperate'}
    ];
    //全局变量：全部设备信息
    //var allDeviceData = [];

    //获取表格数据
    getTableData();
    function getTableData() {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getMeun/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(cols, result.data);
                } else {
                    layer.msg(result.stateMsg);
                }

            }
        })
    }

    //渲染表格
    function renderTable(cols, data) {
        table.render({
            elem: '.settingTable'
            , id: 'menu-table'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarMenu'
            , defaultToolbar: ['filter']
            , cols: [cols]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(setMenuTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'addArea') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增区域",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    form.render();
                    // 图标选择器
                    iconPicker.render({
                        elem: '#iconPicker',
                        // 数据类型：fontClass/unicode，推荐使用fontClass
                        type: 'fontClass',
                        search: true,
                        page: true,
                        limit: 12,
                        // 点击回调
                        click: function (data) {
                            console.log(data);
                        },
                        // 渲染成功后的回调
                        success: function(d) {
                            // console.log(d);
                        }
                    });
                }
            });
            form.on('submit(AddForm)', function(res){
                // console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                addMenus(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            $(".addMenus button[type='cancel']").click(function(){
                layer.close(layerIdx);
                return false;
            });
        }
    });


    //监听工具条
    table.on('tool(setMenuTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteMenus(obj,data);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowEdit').html(),
                success: function(){
                    form.render();
                    $("#iconPicker2").val(data.ioce); // 如果有icon就赋值
                    iconPicker.render({
                        elem: '#iconPicker2',
                        // 数据类型：fontClass/unicode，推荐使用fontClass
                        type: 'fontClass',
                        search: true,
                        page: true,
                        limit: 12,
                        // 点击回调
                        click: function (data) {},
                        // 渲染成功后的回调
                        success: function(d) {}
                    });
                }
            });
            form.val("rowEditForm", data);
            form.on('submit(rowEditForm)', function(res){
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                updateMenus(obj,res.field);
                layer.close(layerIdx);
                return false;
            });
            $(".editMenus button[type='cancel']").click(function(){
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //新增
    function addMenus(dataObj) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/addMeun/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteMenus(obj,data){
        $.ajax({
            url: config.motorBaseUrl + "/area_info/delete/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete',obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    //更新
    function updateMenus(obj,data) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/updMeun/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable("update",obj,data);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function tableReload() {
        table.reload("menu-table", {
            url: config.motorBaseUrl + "/sys/getMeun/v1.0"
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    }

    function refreshTable(type,obj,data){
        if(type == "update"){
            obj.update(data); //同步更新缓存对应的值
        }else if(type == "delete"){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }

});
